indexApp
    .controller(
        'MLdataPRE',
        function($scope, $http, $timeout,$interval) {
            //$scope.url = "http://119.167.221.16:23000/";
            $scope.url = "http://127.0.0.1:3000/";
            /**
             * 从cookie中获取taskId
             */
            $scope.taskId = "";
            function getCookie(name) {
                var arr=document.cookie.split('; ');
                for(var i = 0 ; i < arr.length; i ++){
                    var arr2=arr[i].split('=');
                    if(arr2[0]==name){
                        return arr2[1];
                    }
                }
                return '';
            }
            $scope.taskId = getCookie("taskId");
            $scope.taskConfig = {
                taskId : null,
                taskName : "计算任务",
                description : "创建基于公式和规则的数据计算任务。",
                creator : "lijiajie",
                createTime : null,
                finishTime : null,
                dbName : null,
                tableName : null,
                formula : null,
                rules : null,
                taskTableName : null,
                taskGlobalTableName : null,
                taskProgressRate: null
            };

            $scope.datasetconf={
                name:null,
                describe:null,
                UUID:$scope.taskId
            };
            $scope.currentMySQLTable={
                name:null,
                method:null,
                database:"data_analysis_db",
                UUID:$scope.taskId,
                itemList:null,
                K:null
            };
            $scope.currentMySQLTablePre={
                name:null,
                database:"preModel"
            };
            $scope.deletTable={
                tablenames:null,
                uid:$scope.taskId,
                lableTableName:null,
                labelDes:null
            };
            $scope.mysqlDbInfoVisible=false;
            $scope.normList=["min-max标准化","Z-score标准化方法"];
            $scope.MissingList=["均值填补","0填补"];
            $scope.mysqlTableSampleData=[];
            $scope.mysqlTableSampleDataPre=[];
            $scope.dbInfoList=[];
            $scope.selectedDatabaseIndex=null;
            $scope.MissingIndex=null;
            $scope.normalizationIndex=null;
            $scope.tableItem=[];
            $scope.tableItemPre=[];
            $scope.countItem=[];
            $scope.countItemPre=[];
            $scope.itemType={};
            $scope.itemTypePre={};
            $scope.selectItemList=[];
            $scope.lockButton=false;
            $scope.missingPreLock=false;
            $scope.pcaShow=false;
            $scope.setLable=false;
            $scope.lableShow=function () {
                $scope.setLable=true;
            };
            var selectItemList=[];
            /**
             * 创建新计算任务
             */
            $scope.apiCreateTask = 'cal/config';
            $scope.flagTag = 0;
            var rulaFlag = 0;
            var formulaFlag = 1;
            var sym = "";

            $scope.textareaStartPos = 0;
            $scope.textareaEndPos = 0;
            $scope.getCurrentPos = function (e) {
                var field = e.target;
                $scope.textareaStartPos = field.selectionEnd;
                /* 插入时 不使用插入值替换选中区域，仅从光标终止处插入字符
                    $scope.textareaStartPos = field.selectionStart;
                */
                $scope.textareaEndPos = field.selectionEnd;
                // console.log("start", $scope.textareaStartPos);
                // console.log("end", $scope.textareaEndPos);
            }
            $scope.movePosToEnd = function () {
                if (rulaFlag == 0 && formulaFlag == 1){
                    $scope.textareaStartPos = $scope.formula1.length;
                    $scope.textareaEndPos = $scope.formula1.length;
                }else if(rulaFlag == 1 && formulaFlag == 0){
                    $scope.textareaStartPos = $scope.rula.length;
                    $scope.textareaEndPos = $scope.rula.length;
                }
            }


            /**
             * 封装公式和规则
             */

            $scope.packageJson = function (sym) {

                var start = $scope.textareaStartPos;
                var end = $scope.textareaEndPos;
                if (sym != "\n") {
                    sym = sym + " ";
                }
                if (rulaFlag == 0 && formulaFlag == 1) {
                    if ($scope.formula1.slice((start-1)>0 ? (start-1): 0, start) != " ") {
                        sym = " " + sym;
                    }
                    $scope.formula1 = $scope.formula1.slice(0, start) + sym + $scope.formula1.slice(end);
                } else if (rulaFlag == 1 && formulaFlag == 0) {
                    if ($scope.rula.slice((start-1)>0 ? (start-1): 0, start) != " ") {
                        sym = " " + sym;
                    }
                    $scope.rula = $scope.rula.slice(0, start) + sym + $scope.rula.slice(end);
                }
                $scope.movePosToEnd();
                console.log("formula", $scope.formula1);
                console.log("rula", $scope.rula);
            }

            $scope.updateSubject = function(flags, id, type) {
                var start = $scope.textareaStartPos;
                var end = $scope.textareaEndPos;

                if (rulaFlag == 0){
                    if (flags == '1'){
                        if ($scope.formula1.slice((start-1)>0 ? (start-1): 0, start) != " ") {
                            id = " " + id;
                        }
                        $scope.formula1 = $scope.formula1.slice(0, start) + id + " " + $scope.formula1.slice(end);
                    }
                    else{
                        $scope.formula1 = $scope.formula1.replace(id,'');
                    }
                }else{
                    if (flags == '1'){
                        if ($scope.rula.slice((start-1)>0 ? (start-1): 0, start) != " ") {
                            id = " " + id;
                        }
                        $scope.rula = $scope.rula.slice(0, start) + id + " " + $scope.rula.slice(end);
                    }
                    else{
                        $scope.rula = $scope.rula.replace(id,'');
                    }
                }
                $scope.movePosToEnd();
            }

            $scope.addSpace = function () {
                var formula1str = $scope.formula1;
                if (formula1str != ""
                    && formula1str.charAt(formula1str.length-1) != " "
                    && formula1str.charAt(formula1str.length-1) != "\n") {
                    $scope.formula1 = $scope.formula1 + " ";
                }
                var rulaStr = $scope.rula;
                if (rulaStr != ""
                    && rulaStr.charAt(rulaStr.length-1) != " "
                    && rulaStr.charAt(rulaStr.length-1) != "\n") {
                    $scope.rula = $scope.rula + " ";
                }
            }


            $scope.rula = ""
            $scope.rulaInput = function() {
                if (formulaFlag == 1 && rulaFlag == 0) {
                    rulaFlag = 1;
                    formulaFlag = 0;
                    $scope.movePosToEnd();
                }
                $scope.addSpace();
            }

            $scope.formulaInput = function() {
                if (formulaFlag == 0 && rulaFlag == 1) {
                    rulaFlag = 0;
                    formulaFlag = 1;
                    $scope.movePosToEnd();
                }
                $scope.addSpace();
            }
            $scope.formula1 = "";

            /**
             * 创建任务
             */
            $scope.labelDes=null;
            $scope.submitJson = function() {
                $scope.taskConfig["taskId"]=$scope.taskId;
                $scope.taskConfig["formula"] = $scope.formula1;
                $scope.taskConfig["rules"] = $scope.rula;
                $scope.taskConfig["tableName"] = $scope.dbInfoList[parseInt($scope.selectedDatabaseIndex)];
                //$scope.taskConfig["dbName"] = "jck_basic_db";
                //console.log("sub_dbNameList",$scope.dbNameList[parseInt($scope.selectedDatabaseIndex)]);
                $scope.taskConfig["dbName"] = "data_analysis_db";
                $scope.taskToken01 = true;
                $scope.taskToken02 = true;
                $http({
                    method : 'POST',
                    headers : {
                        'Content-Type' : 'application/json',
                    },
                    url : 'cal/config',
                    data : $scope.taskConfig,

                }).then(function(resp, status) {
                    $scope.result = resp.data["tablename"];
                    $scope.deletTable.lableTableName=$scope.result;
                    $scope.taskConfig.taskId = resp.data["taskId"];
                    console.log("labletablename",$scope.result);
                    console.log(resp.data.taskId);
                    $scope.status = status;
                    swal({
                        title: '标签设置成功！',
                        timer: 2000
                    });
                    $scope.setLable=false;

                }, function(resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
            }

            /**
             * 切换数据库或表时，清空已输入的公式和规则
             */
            $scope.clearFormulaAndRula = function () {
                $scope.formula1 = "";
                $scope.rula = "";
            }
            $scope.getTableName=function () {
                $http({
                    method: 'post',
                    url: $scope.url + 'gettablename',
                    data:$scope.datasetconf
                }).then(function (resp, status) {
                    console.log(resp.data);
                    $scope.dbInfoList=resp.data.res;
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
            };
            $scope.getDataSample=function () {
                $scope.currentMySQLTable.name=$scope.dbInfoList[parseInt($scope.selectedDatabaseIndex)];
                $scope.tableItem=[];
                $scope.mysqlTableSampleData=[];
                $scope.itemType={};
                $scope.countItem=[];
                $http({
                    method: 'post',
                    url: $scope.url + 'gettableItem',
                    data:$scope.currentMySQLTable
                }).then(function (resp, status) {
                    $scope.tableItem=resp.data.res;
                    console.log($scope.tableItem);
                    for (var i = 0; i<$scope.tableItem.length; i++) {
                        $scope.countItem.push(i.toString());
                    }
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
                $http({
                    method: 'post',
                    url: $scope.url + 'getsampledata',
                    data:$scope.currentMySQLTable
                }).then(function (resp, status) {
                    $scope.mysqlTableSampleData=resp.data.res;
                    console.log($scope.mysqlTableSampleData);
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
                $http({
                    method: 'post',
                    url: $scope.url + 'getitemtype',
                    data:$scope.currentMySQLTable
                }).then(function (resp, status) {
                    $scope.itemType=resp.data.res;
                    console.log("type",$scope.itemType);
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });

            };
            $scope.getDataSamplePre=function () {
                $scope.tableItemPre=[];
                $scope.mysqlTableSampleDataPre=[];
                $scope.itemTypePre={};
                $scope.countItemPre=[];
                $http({
                    method: 'post',
                    url: $scope.url + 'gettableItem',
                    data:$scope.currentMySQLTablePre
                }).then(function (resp, status) {
                    $scope.tableItemPre=resp.data.res;
                    console.log($scope.tableItemPre);
                    for (var i = 0; i<$scope.tableItemPre.length; i++) {
                        $scope.countItemPre.push(i.toString());
                    }
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
                $http({
                    method: 'post',
                    url: $scope.url + 'getsampledata',
                    data:$scope.currentMySQLTablePre
                }).then(function (resp, status) {
                    $scope.mysqlTableSampleDataPre=resp.data.res;
                    console.log($scope.mysqlTableSampleDataPre);
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
            };
            $scope.preMissing=function () {
                var analysisBtn = document.getElementById("analysis-btn");
                var time = Math.ceil((Math.random() + 2)*2000);
                analysisBtn.classList.add("click");
                $scope.currentMySQLTable.method=parseInt($scope.MissingIndex);
                $scope.currentMySQLTable.UUID=$scope.datasetconf.UUID;
                $http({
                    method: 'post',
                    url: $scope.url + 'missingdata',
                    data:$scope.currentMySQLTable
                }).then(function (resp, status) {
                    $scope.currentMySQLTablePre.name=resp.data.targetTableName;
                    $scope.deletTable.tablenames=resp.data.targetTableName+";";
                    console.log("type",$scope.currentMySQLTablePre.name);
                    //$scope.getDataSamplePre();
                    $timeout(function () {
                        $scope.getDataSamplePre();
                        $scope.mysqlDbInfoVisible=true;
                        $scope.missingPreLock=true;
                        analysisBtn.classList.remove('click');
                    }, time);
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
                
            };
            $scope.preNorm=function () {
                var analysisBtn = document.getElementById("pre_norm");
                var time = Math.ceil((Math.random() + 2)*1000);
                $scope.currentMySQLTable.name=$scope.currentMySQLTablePre.name;
                $scope.currentMySQLTable.method=parseInt($scope.normalizationIndex);
                $http({
                    method: 'post',
                    url: $scope.url + 'normdata',
                    data:$scope.currentMySQLTable
                }).then(function (resp, status) {
                    $scope.currentMySQLTablePre.name=resp.data.targetTableName;
                    $scope.deletTable.tablenames+=resp.data.targetTableName+";";
                    console.log("tablename",$scope.currentMySQLTablePre.name);
                    $timeout(function () {
                        $scope.getDataSamplePre();
                        analysisBtn.classList.remove('click');
                    }, time);
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });

            };
            $scope.pcaSet=function(){
                $scope.pcaShow=true;
            };
            $scope.startPCA=function(){
                $scope.currentMySQLTable.name=$scope.currentMySQLTablePre.name;
                $scope.currentMySQLTable.K=parseInt($scope.currentMySQLTable.K);
                $http({
                    method: 'post',
                    url: $scope.url + 'startpca',
                    data:$scope.currentMySQLTable
                }).then(function (resp, status) {
                    $scope.currentMySQLTablePre.name=resp.data.targetTableName;
                    $scope.deletTable.tablenames+=resp.data.targetTableName+";";
                    console.log("tablename",$scope.currentMySQLTablePre.name);
                    $scope.getDataSamplePre();
                    $scope.mysqlDbInfoVisible=true;
                    $scope.missingPreLock=true;
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
            };
            $scope.updateKeys = function($event, id) {
                console.log("event", id);
                $scope.checkflag2="1";
                var checkbox = $event.target;
                var action = (checkbox.checked ? 'add' : 'remove');
                console.log(checkbox,action);
                if(action=='add'){
                    selectItemList.push(id);
                    console.log(id);
                    console.log(selectItemList);
                }
                else{
                    var index=selectItemList.indexOf(id);
                    console.log(index);
                    selectItemList.splice(index,1);
                    console.log(selectItemList);
                }
            };
            $scope.selectAll=function ($event,data) {
                var inputs =  document.getElementsByName("CB");
                for(var i = 0;i<inputs.length;i++){
                    inputs[i].checked = true;
                }
                $scope.selectItemList=data;
                selectItemList=angular.copy($scope.selectItemList);
                console.log($scope.selectItemList);

            };
            $scope.unselectAll=function ($event) {
                var inputs =  document.getElementsByName("CB");
                for(var i = 0;i<inputs.length;i++){
                    inputs[i].checked = false;
                }
                $scope.selectItemList=[];
                selectItemList=angular.copy($scope.selectItemList);
                console.log($scope.selectItemList);

            };
            $scope.buildJson=function () {
                $scope.lockButton=true;
                $scope.currentMySQLTable.itemList=selectItemList;
                console.log(selectItemList);
            };
            $scope.start=function(){
                $scope.deletTable.labelDes=$scope.labelDes;
                console.log($scope.deletTable);
                $http({
                    method: 'post',
                    url: $scope.url + 'recordtablename',
                    data:$scope.deletTable
                }).then(function (resp, status) {
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
                window.location=encodeURI("Modelling.html?tablename="+$scope.currentMySQLTablePre.name+"&taskId="+$scope.datasetconf.UUID+"&oldtablename="+$scope.dbInfoList[parseInt($scope.selectedDatabaseIndex)]);
            };
            $scope.predictstart=function(){
                $http({
                    method: 'post',
                    url: $scope.url + 'updatetablename',
                    data:$scope.deletTable
                }).then(function (resp, status) {
                    $scope.status = status;
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
                window.location=encodeURI("predictData.html?tablename="+$scope.currentMySQLTablePre.name+"&oldtablename="+$scope.dbInfoList[parseInt($scope.selectedDatabaseIndex)]+"&taskId="+$scope.datasetconf.UUID);
            };
            /**
             * 建模相关控制器
             */
        });